package com.chenshu.shop.controller.admin;

import com.chenshu.shop.common.PageUtil;
import com.chenshu.shop.model.Good;
import com.chenshu.shop.model.Top;
import com.chenshu.shop.model.Type;
import com.chenshu.shop.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-06
 * Time：09:02
 */
@Controller
@RequestMapping("/admin")
public class GoodController_admin {
    @Autowired
    GoodService goodService;

    @RequestMapping("/redirect/index")
    public String getIndexPage() {
        return "redirect:/admin/index.jsp";
    }

    /**
     * 在good_list.jsp显示所有商品
     *
     * @param request
     * @param type
     * @return
     */
    @RequestMapping("/goodList")
    public String getPageGoods(HttpServletRequest request,
                               @RequestParam(defaultValue = "0", required = false) Integer type,
                               @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageIndex,
                               @RequestParam(value = "size", defaultValue = "4", required = false) Integer pageSize) {
        request.setAttribute("flag", 2);
        request.setAttribute("page", pageIndex);
        //获取今日推荐的商品Id
        List<Integer> topIds = goodService.getTopIds();
        if (type == 0) {
            //全部商品
            List<Good> goodList = goodService.getPageGoods(pageIndex, pageSize);
            //遍历商品列表，设置top字段
            for(Good good: goodList) {
                if (topIds.contains(good.getId())) {
                    good.setTop(true);
                }
            }
            request.setAttribute("goodList", goodList);
            Integer count = goodService.getGoodsCount();
            //生成分页条
            String pageTool = PageUtil.getPageTool(request, count, pageIndex, pageSize);
            request.setAttribute("pageTool", pageTool);
        } else {
            //今日推荐
            List<Good> goodList = goodService.getPageGoodsByIds(topIds, pageIndex, pageSize);
            for(Good good: goodList) {
                if (topIds.contains(good.getId())) {
                    good.setTop(true);
                }
            }
            request.setAttribute("goodList", goodList);
            int count = topIds.size();
            //生成分页条
            String pageTool = PageUtil.getPageTool(request, count, pageIndex, pageSize);
            request.setAttribute("pageTool", pageTool);
        }
        return "forward:/admin/good_list.jsp";
    }

    /**
     * 跳转到商品编辑页
     * @param request
     * @param id
     * @param page：用于定位当前页码
     * @return
     */
    @RequestMapping("/goodEdit")
    public String EditGood(HttpServletRequest request, Integer id, Integer page) {
        request.setAttribute("page", page);
        //查询货物信息
        Good good = goodService.getGoodById(id);
        request.setAttribute("good", good);
        //查询所有类目
        List<Type> typeList = goodService.getAllTypes();
        request.setAttribute("typeList", typeList);
        return "forward:/admin/good_edit.jsp";
    }

    /**
     * 编辑商品
     * @param good
     * @param page：用于定位当前页码
     * @param image
     * @return
     */
    @RequestMapping("/goodUpdate")
    public String updateGood(Good good, Integer page,
                             @RequestPart("file")MultipartFile image) {
        String newPath = "/Users/chenshu/Code/project/shop/src/main/webapp/upload/";
        if (image != null && !image.isEmpty()) {
            String originalFileName = image.getOriginalFilename();
            int suffixIndex = originalFileName.lastIndexOf('.');
            String suffix = originalFileName.substring(suffixIndex);
            //使用UUID命名图片
            String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            try {
                image.transferTo(new File(newPath + fileName));
                good.setCover("../upload/" + fileName);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (goodService.updateGoodInfo(good)) {
            return "redirect:/admin/goodList?page=" + page;
        }
        return "redirect/admin/goodEdit";
    }

    /**
     *
     * @param goodId：商品Id
     * @param page：页码
     * @return
     */
    @RequestMapping("/topAdd")
    public String addGoodToTop(@RequestParam("id") Integer goodId, Integer page) {
        Top top = new Top();
        top.setGoodId(goodId);
        top.setType(1);
        goodService.addTop(top);
        return "redirect:/admin/goodList?page=" + page;
    }
    @RequestMapping("/topRemove")
    public String RemoveGoodFromTop(@RequestParam("id") Integer goodId, Integer page) {
        goodService.deleteTop(goodId);
        return "redirect:/admin/goodList?page=" + page;
    }

    @RequestMapping("/goodAdd")
    public String addGood(HttpServletRequest request) {
        List<Type> typeList = goodService.getAllTypes();
        request.setAttribute("typeList", typeList);
        return "forward:/admin/good_add.jsp";
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE)
    @RequestMapping("/goodSave")
    public String saveGood(@RequestPart("file") MultipartFile image, Good good) {
        //图片保存路径
        String newPath = "/Users/chenshu/Code/project/shop/src/main/webapp/upload/";
        String originalFileName = image.getOriginalFilename();
        //源文件后缀
        int suffixIndex = originalFileName.lastIndexOf('.');
        String suffix = originalFileName.substring(suffixIndex);
        //新生成的唯一文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        try {
            //将图片上传到本地
            image.transferTo(new File(newPath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //设置数据库中的封面url
        good.setCover("../upload/" + fileName);
        //将数据存入数据库
        goodService.addGoods(good);
        int totalPage = goodService.getTotalPage();
        return "redirect:/admin/goodList?page=" + totalPage;
    }

    @RequestMapping("/goodDelete")
    public String deleteGoods(@RequestParam("id") Integer goodsId, Integer page) {
        //删除商品
        goodService.deleteGoods(goodsId);
        return "redirect:/admin/goodList?page=" + page;
    }

}
